package com.LeeCode;

/**
 * 平衡二叉树
 */

public class Code110 {
    public static void main(String[] args) {
        Integer[] arr = {1, 2, 2, 3, 3, null, null, 4, 4};
        TreeNode root = Utils.buildTree(arr);
        System.out.println(new Code110().isBalanced(root));
    }

    public boolean isBalanced(TreeNode root) {
        return height(root) != -1;
    }

    private int height(TreeNode root) {
        if (root == null) return 0;
        int left = height(root.left);
        if (left == -1) return -1;
        int right = height(root.right);
        if (right == -1 || Math.abs(left - right) > 1) return -1;
        return Math.max(left, right) + 1;
    }
}
